package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IStrategyThemeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;


@Service
public class StrategyThemeServiceImpl implements IStrategyThemeService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private StrategyThemeRepository repository;


    @Override
    public Page<StrategyTheme> query(QueryObject qo) {


        // 1. 查询对象
        Query query = new Query();

        // 2. 封装参数
        // 总条数
        long count = template.count(query, StrategyTheme.class);
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageable);

        List<StrategyTheme> list = template.find(query, StrategyTheme.class);

        return new PageImpl<>(list,pageable,count);
    }

    @Override
    public void saveOrUpdate(StrategyTheme strategyTheme) {
        if (StringUtils.hasLength(strategyTheme.getId())){
            repository.save(strategyTheme);
        }else {
            strategyTheme.setId(null);
            repository.save(strategyTheme);
        }
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyTheme get(String themeId) {
        return repository.findById(themeId).orElse(null);
    }

    @Override
    public List<StrategyTheme> list() {

        return repository.findAll();
    }


}
